package com.etl.dataflow.scheduler.exception;

import com.etl.dataflow.common.exception.ServiceException;
import com.etl.dataflow.common.response.R;
import com.etl.dataflow.common.util.ExceptionUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author dx
 * @since 2022/4/20
 */
@RestControllerAdvice(basePackages = {"com.etl.dataflow.scheduler.communication", "com.etl.dataflow.scheduler.admin"})
public class ErrorHandler {

    @ExceptionHandler(value = Exception.class)
    public R defaultExceptionHandler(Exception e) {
        e.printStackTrace();
        return R.error().setMsg(ExceptionUtil.getFullStackTrace(e));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleParameterValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            sb.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append(";");
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return R.error().setMsg(sb.toString());
    }

    @ExceptionHandler(ServiceException.class)
    public R handleServiceException(ServiceException e) {
        return R.error().setCode(e.getCode()).setMsg(e.getMsg());
    }
}
